//
// Created by liuj on 17-5-24.
//

#include <android/bitmap.h>
#include <jni.h>
#include "stackblur.h"

JNIEXPORT void JNICALL Java_com_liang_liuj_blur_StackBlur_blurPixels(
    JNIEnv *env, jclass obj, jintArray arrIn, jint w, jint h, jint r )
{
    jint *pixels;
    // cpp:
    // pix = (env)->GetIntArrayElements(arrIn, 0);
    pixels = (*env)->GetIntArrayElements(env, arrIn, 0);
    if (pixels == NULL) {
        return;
    }

    // Start
    pixels = blur_ARGB_8888(pixels, w, h, r);
    // End

    // if return:
    // int size = w * h;
    // jintArray result = env->NewIntArray(size);
    // env->SetIntArrayRegion(result, 0, size, pix);
    // cpp:
    // (env)->ReleaseIntArrayElements(arrIn, pix, 0);
    (*env)->ReleaseIntArrayElements(env, arrIn, pixels, 0);
}

JNIEXPORT void JNICALL Java_com_liang_liuj_blur_StackBlur_blurBitmap(
    JNIEnv *env, jclass obj, jobject bitmapIn, jint r )
{
    AndroidBitmapInfo infoIn;
    void *pixels;

    // Get image info
    if (AndroidBitmap_getInfo(env, bitmapIn, &infoIn) != ANDROID_BITMAP_RESULT_SUCCESS) {
        //("AndroidBitmap_getInfo failed!");
        return;
    }

    // Check image
    if (infoIn.format != ANDROID_BITMAP_FORMAT_RGBA_8888 &&
        infoIn.format != ANDROID_BITMAP_FORMAT_RGB_565) {
        //("Only support ANDROID_BITMAP_FORMAT_RGBA_8888 and ANDROID_BITMAP_FORMAT_RGB_565");
        return;
    }
    // Lock all images
    if (AndroidBitmap_lockPixels(env, bitmapIn, &pixels) != ANDROID_BITMAP_RESULT_SUCCESS) {
        //("AndroidBitmap_lockPixels failed!");
        return;
    }
    // height width
    int h = infoIn.height;
    int w = infoIn.width;

    // Start
    if (infoIn.format == ANDROID_BITMAP_FORMAT_RGBA_8888) {
        pixels = blur_ARGB_8888((int *) pixels, w, h, r);
    } else if (infoIn.format == ANDROID_BITMAP_FORMAT_RGB_565) {
        pixels = blur_RGB_565((short *) pixels, w, h, r);
    }

    // End

    // Unlocks everything
    AndroidBitmap_unlockPixels(env, bitmapIn);
}